
import TimeObserver from "./TimeObserver";
export default abstract class TimeManager  {


    constructor(interval:number){
        this.interval = interval;
    }

    private interval: number = 1;


    private intervalID = 0;

    //以秒为单位的观察者。
    private secondObserverList:Array<TimeObserver> = [];

    addTimeListener(observer:TimeObserver){
        this.secondObserverList.push(observer);
    }

    removeTimeListener(observer:TimeObserver){
        for (let index = 0; index < this.secondObserverList.length; index++) {
            const element = this.secondObserverList[index];
            if(observer === element){
                this.secondObserverList.splice(index,1);
                break;
            }
        }
    }


    start(){
        this.intervalID = setInterval(() => {
            this.updateInterval();
        }, this.interval*1000);
    }

    stop(){
        if( this.intervalID > 0){
            cc.log("onDestroy clearInterval  this.intervalID ",this.intervalID);
            clearInterval( this.intervalID );
        }
    }


    onDestroy(){
        this.clear();
        this.stop();
    }

    updateInterval(){
        // cc.log("  this.secondObserverList.length ", this.secondObserverList.length);
        for (let index = 0; index < this.secondObserverList.length; index++) {
            const element:TimeObserver = this.secondObserverList[index];
            element.update(this.interval);
            if(element.getTime() === 0 && element.isAutoDelete()){
                element.stop();
            }   
        }
    }

    private clear(){
        this.secondObserverList = [];
    }

}
